#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import pandas as pd
import sklearn.datasets as ds
from sklearn.cluster import KMeans

data1 = np.loadtxt('dataset_circles.csv',delimiter=",")

data = data1[:,0:2]
y = data1[:,2]

r = (data[:,0]**2 + data[:,1]**2)**0.5

data2 = np.zeros((400,2))
data2[:,0] = r


centers = 4
N = 400
km = KMeans(n_clusters=centers,random_state=28)
km.fit(data2)
y_hat = km.predict(data2)
print("所有样本距离聚簇中心点的总距离和:",km.inertia_)
print("距离聚簇中心点的平均距离:",(km.inertia_/N))
print("聚簇中心点:",km.cluster_centers_)

def expandBorder(a,b):
    d = (b-a) * 0.1
    return a-d, b+d

cm = mpl.colors.ListedColormap(list("rgbmyc"))
plt.figure(figsize=(6,5),facecolor="w")
plt.subplot(221)
plt.scatter(data[:,0],data[:,1],c=y,s=15,cmap=cm,edgecolors="none")

x1_min,x2_min = np.min(data,axis=0)
x1_max,x2_max = np.max(data,axis=0)
x1_min,x1_max = expandBorder(x1_min,x1_max)
x2_min,x2_max = expandBorder(x2_min,x2_max)
plt.xlim((x1_min,x1_max))
plt.ylim((x2_min,x2_max))
plt.title("yuanshishujv")
plt.grid(1)

plt.subplot(222)
plt.scatter(data[:,0],data[:,1],c=y_hat,s=15,cmap=cm,edgecolors="none")
plt.xlim((x1_min,x1_max))
plt.ylim((x2_min,x2_max))
plt.title("kmeans")
plt.grid(1)

